import DayJS from "dayjs";
import React from "react";
import { adminQueryAllTenants } from "../../../common/apis";
import { tenantsStatus } from "../../../common/constant";
import request from "../../../common/http";
import { goTo } from "../../../common/utils";
import TenantAdd from "./tenant-add";
import TenantList from "./tenant-list";
import SearchBar from "./tenant-search";

import "./index.less";

class Tenants extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tenantList: [],
      keyword: "",
      pageIndex: 1,
      pageSize: 1000,
      isShowLoading: false,
    };
  }

  componentDidMount() {
    this.initData();
  }

  /**
   * 初始化数据
   */
  initData = async () => {
    await this.getTenantList();
  };

  /**
   * 获取租户列表
   */
  getTenantList = async () => {
    this.setState({ isShowLoading: true });
    const { keyword, pageIndex, pageSize } = this.state;
    let { data } = await request.post(adminQueryAllTenants, {
      keyword,
      pageIndex,
      pageSize,
    });
    data = data?.list;

    if (Array.isArray(data)) {
      this.setState({
        tenantList: data.map((tenantItem) => {
          tenantItem.createdAt = DayJS(tenantItem.createdAt).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          tenantItem.tenantStatusText =
            tenantsStatus[tenantItem.tenantStatus]?.title || "";
          return tenantItem;
        }),
        isShowLoading: false,
      });
      return;
    }
    this.setState({ isShowLoading: false });
  };

  /**
   * 搜索
   */
  onSearch = ({ keyword }) => {
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      this.setState(
        {
          keyword:
            typeof keyword === "undefined" ? this.state.keyword : keyword,
        },
        this.getTenantList
      );
    }, 500);
  };

  /**
   * 跳转租户详情页
   * @param {string} tenantCode 租户编码
   */
  showTenantDetails = (tenantCode) => {
    goTo("/tenant/details?tenantCode=" + tenantCode);
  };

  /**
   * 阻止事件冒泡
   * @param {event} e
   */
  stopPropagation = (e) => {
    e && e.stopPropagation();
  };

  /**
   * 新增租户
   */
  addTenant = () => {
    goTo("/tenant/edit");
  };

  render() {
    const { tenantList, isShowLoading } = this.state;

    return (
      <div className="baby-love-admin-tenant-list">
        <SearchBar onSearch={this.onSearch} />
        <TenantList
          tenantList={tenantList}
          stopPropagation={this.stopPropagation}
          showTenantDetails={this.showTenantDetails}
          isShowLoading={isShowLoading}
          getTenantList={this.getTenantList}
        />
        {/* 新增租户图标 */}
        <TenantAdd addTenant={this.addTenant} />
      </div>
    );
  }
}

export default Tenants;
